import React, { Component } from 'react';

class Drag extends Component {
  state = {
    mousePos: {
      x: 0,
      y: 0
    },
    isDrag: false,
    styleObj: {

    }
  }
  handleMouseDown = e => {
    const { styleObj } = this.state
    this.setState({
      mousePos: {
        x: e.offsetX,
        y: e.offsetY
      },
      isDrag: true,
      styleObj: {
        ...styleObj,
        position: 'absolute'
      }
    })
  }
  handleMouseMove = e => {
    const { isDrag, mousePos, styleObj } = this.state
    if(isDrag) {
      this.setState({
        styleObj: {
          ...styleObj,
          left: e.pageX - mousePos.x,
          top: e.pageY - mousePos.y,
        }
      })
    }
  }
  handleMouseUp = () => {
    this.setState({
      isDrag: false
    })
  }
  render() {
    const { styleObj } = this.state
    return (
      <div>
        <div className="box" ref={(ref) => this.box = ref} style={ styleObj }></div>
      </div>
    );
  }
  componentDidMount() {
    this.box.addEventListener('mousedown', this.handleMouseDown)
    document.addEventListener('mousemove', this.handleMouseMove)
    document.addEventListener('mouseup', this.handleMouseUp)
  }

  componentWillUnmount() {
    this.box.removeEventListener('mousedown', this.handleMouseDown)
    document.removeEventListener('mousemove', this.handleMouseMove)
    document.removeEventListener('mouseup', this.handleMouseUp)
  }
}

export default Drag;
